package com.duyutian.common;

import com.duyutian.util.JSONUtil;
import com.jfinal.json.JFinalJson;
import com.jfinal.plugin.activerecord.Record;

import java.util.List;
import java.util.Map;


public class ServiceResult {
    //成功返回2--
    public static int RESULT_STATUS_200 = 200;
    public static int SYS_ERROR = 9999;


    private int ret;
    private String msg;
    private Object data;

    public ServiceResult() {
    }

    public ServiceResult(int ret, String msg, Object data) {
        this.ret = ret;
        this.msg = msg;
        this.data = data;
    }

    public int getRet() {
        return ret;
    }

    public void setRet(int ret) {
        this.ret = ret;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static ServiceResult success() {
        ServiceResult rs = new ServiceResult(RESULT_STATUS_200, "success", null);
        return rs;
    }

    public static ServiceResult success(Object data) {
        ServiceResult rs = new ServiceResult(RESULT_STATUS_200, "success", data);
        return rs;
    }

    public static ServiceResult error(int code, String msg) {
        ServiceResult rs = new ServiceResult(code, msg, null);
        return rs;
    }


    public static ServiceResult error(int code, String msg, Object data) {
        ServiceResult rs = new ServiceResult(code, msg, data);
        return rs;
    }

    public static ServiceResult sysError() {
        ServiceResult rs = new ServiceResult(SYS_ERROR, "系统错误", null);
        return rs;
    }


    public String toJson() {
        String ss = JFinalJson.getJson().toJson(this);
        return ss;
    }

    /**
     * 如果data 中包含jfinal  record 对象需要处理
     *
     * @return
     */
    public ServiceResult rsFormat() {
        if (this.data != null) {
            String ss = JFinalJson.getJson().toJson(getData());
            System.out.println(ss);
            if (this.data instanceof List) {
                setData(JSONUtil.toList(ss, Map.class));
            } else {
                setData(JSONUtil.toMap(ss));
            }

        }
        return this;
    }

        /*直接返回数据 用于数据表格*/
    public static List<Map> rsFormat1(List<Record> record) {
        String ss = JFinalJson.getJson().toJson(record);
        return JSONUtil.toList(ss, Map.class);
    }

    public static String getJson(Object json){
        return JFinalJson.getJson().toJson(json);
    }
}
